package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.KGXcollectionData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.event.RefreshRoomDeviceEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.adapter.EnviromentScrollAdapter;
import com.qiantu.phone.ui.adapter.LoadDeviceAdapter;
import com.qiantu.phone.widget.StatusLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class KGXLoadDeviceActivity extends AppActivity implements OnRefreshLoadMoreListener, StatusAction {

    public final static int TYPE_CONTROLLER = 0x1;
    public final static int TYPE_DEVICE = 0x2;

    private int pageIndex = 1;
    private int pageSize = 10;
    //1初始化  2刷新  3加载更多
    private int requestType = 1;
    private StatusLayout mStatusLayout;
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView enviromentRecyclerView;
    private RecyclerView loadDeviceRecyclerView;
    private View deviceViewContainer;

    private EnviromentScrollAdapter mEnviromentAdapter;
    private LoadDeviceAdapter mLoadDeviceAdapter;
    private KGXcollectionData deviceCollectBean;
    private int type;

    private Fragment deviceFragment;
    private FragmentManager mFragmentManager;

    @Log
    public static void start(Context context, KGXcollectionData deviceCollectBean, int type) {
        Intent intent = new Intent(context, KGXLoadDeviceActivity.class);
        intent.putExtra("deviceCollectBean", deviceCollectBean);
        intent.putExtra("type", type);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_load_device_kgx;
    }

    @Override
    protected void initView() {
        setRightTitle(R.string.save);
        EventBus.getDefault().register(this);
        deviceCollectBean = getSerializable("deviceCollectBean");
        type = getInt("type", TYPE_CONTROLLER);
        switch (type){
            case TYPE_CONTROLLER:
                setTitle(R.string.load_device);
                break;
            case TYPE_DEVICE:
                setTitle(R.string.belong_controller);
                break;
        }
        mStatusLayout = findViewById(R.id.status_layout);
        smartRefreshLayout = findViewById(R.id.smart_refresh_layout);
        enviromentRecyclerView = findViewById(R.id.environment_recycler_view);
        loadDeviceRecyclerView = findViewById(R.id.load_device_recycler_view);
        deviceViewContainer = findViewById(R.id.device_view_container);
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        mEnviromentAdapter = new EnviromentScrollAdapter(getContext());
        mEnviromentAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mEnviromentAdapter.getData().get(position);
                DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo(), false);
            }
        });
        enviromentRecyclerView.setAdapter(mEnviromentAdapter);
        enviromentRecyclerView.setLayoutManager(linearLayoutManager);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        loadDeviceRecyclerView.setLayoutManager(gridLayoutManager);
        mLoadDeviceAdapter = new LoadDeviceAdapter(this);
        mLoadDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mLoadDeviceAdapter.getData().get(position);
                mLoadDeviceAdapter.getData().get(position).setIsDisable(!device.getIsDisable());
                mLoadDeviceAdapter.notifyItemChanged(position);
            }
        });
        mLoadDeviceAdapter.setSelectable(true);
        loadDeviceRecyclerView.setAdapter(mLoadDeviceAdapter);
    }

    @Override
    protected void initData() {
        getLoadDevices();
    }

    private void getLoadDevices(){
        List<DeviceBean> data = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerial4KGX(deviceCollectBean.getControllerSerialNo(),deviceCollectBean.getDeviceCollectSerialNo());
        mLoadDeviceAdapter.setData(data);
        enviromentRecyclerView.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshDeviceListEvent(RefreshDeviceListEvent event) {
        getLoadDevices();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestType = 3;
        pageIndex = (int) Math.ceil(((float) mLoadDeviceAdapter.getData().size() / pageSize)) + 1;
        getLoadDevices();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestType = 2;
        pageIndex = 1;
        getLoadDevices();
    }

    @Override
    public void onRightClick(View view) {
        List<String> enables = new ArrayList<>();
        List<String> disalbes = new ArrayList<>();
        for(DeviceBean deviceBean : mLoadDeviceAdapter.getData()){
            if(deviceBean.getIsDisable()){
                disalbes.add(deviceBean.getDeviceSerialNo());
            }else{
                enables.add(deviceBean.getDeviceSerialNo());
            }
        }
        LLHttpManager.updateDeviceEables(new ApplicationLifecycle(), enables, disalbes, new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                for(String serialNo : enables){
                    LLDeviceDBManager.getInstance(getContext()).updateDisable(serialNo,false);
                }
                for(String serialNo : disalbes){
                    LLDeviceDBManager.getInstance(getContext()).updateDisable(serialNo,true);
                }
                EventBus.getDefault().post(new RefreshFloorRoomEvent());
                hideDialog();
                finish();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }
}